/*
 * motor.c
 *
 *  Created on: 2018年3月7日
 *      Author: chen
 */


/* Includes ------------------------------------------------------------------*/
#include "motor.h"

#include "fsl_ftm.h"

#include "peripherals.h"

/* Definitions ---------------------------------------------------------------*/
#define BOARD_FTM_PWM        MOTOR_PERIPHERAL
#define BOARD_FTM_PWM_P      (0U)
#define BOARD_FTM_PWM_N      (1U)

#define BOARD_FTM_CNT        ENCODER_PERIPHERAL

/* Codes ---------------------------------------------------------------------*/
/**
  * @brief  改变电机占空比
  * @param  [in] speedInfo： mSpeed_t结构体
  * @retval None
  */
void Motor_ChangeDuty(mSpeed_t speedInfo)
{
    if(speedInfo.pwm >= 0)
    {
        FTM_UpdatePwmDutycycle(BOARD_FTM_PWM, (ftm_chnl_t)BOARD_FTM_PWM_P, kFTM_EdgeAlignedPwm, speedInfo.pwm);
        FTM_UpdatePwmDutycycle(BOARD_FTM_PWM, (ftm_chnl_t)BOARD_FTM_PWM_N, kFTM_EdgeAlignedPwm, 0);
    }
    else
    {
        FTM_UpdatePwmDutycycle(BOARD_FTM_PWM, (ftm_chnl_t)BOARD_FTM_PWM_P, kFTM_EdgeAlignedPwm, 0);
        FTM_UpdatePwmDutycycle(BOARD_FTM_PWM, (ftm_chnl_t)BOARD_FTM_PWM_N, kFTM_EdgeAlignedPwm, -speedInfo.pwm);
    }

    /* Software trigger to update registers */
    FTM_SetSoftwareTrigger(BOARD_FTM_PWM, true);
}

/**
  * @brief  获取电机转速
  * @param  [in] speedInfo： mSpeed_t结构体
  * @retval None
  */
void Motor_GetCnt(mSpeed_t *speedInfo)
{
    /* 读脉冲 */
    speedInfo->count = FTM_GetQuadDecoderCounterValue(BOARD_FTM_CNT);
    /* 清除脉冲计数 */
    FTM_ClearQuadDecoderCounterValue(BOARD_FTM_CNT);
    /* 读方向 */
    if (FTM_GetQuadDecoderFlags(BOARD_FTM_CNT) & kFTM_QuadDecoderCountingIncreaseFlag)
        speedInfo->dir = true;
    else
        speedInfo->dir = false;
}
